package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.sdk.CloudTalkUserAuthDTO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.property.service.IPropertyHouseHoldInfoService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;


/**
 * <desc>
 *      获取用户设备权限地址队列消费者
 * </desc>
 *
 * @createDate 2018/05/18
 */
@Component
public class CloudTalkSDKUserAuthConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkSDKUserAuthConsumer.class);

    @Autowired
    IPropertyHouseHoldInfoService iPropertyHouseHoldInfoService;

    /**
     * <desc>
     *      获取用户设备权限地址队列消费者
     * </desc>
     * @param message 消息
     * @param channel
     * @author JuGuang.S
     * @createDate 2018/05/18
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_CLOUD_TALK_SDK_USER_SAVE_DEVICE_AUTH_INFO_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_SDK获取用户设备权限地址队列消费者:" + body);
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            CloudTalkUserAuthDTO userAuthDTO = JSON.parseObject(JSON.toJSONString(JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent()).get("data")), CloudTalkUserAuthDTO.class);
            if (userAuthDTO != null) {
                String authUserId = userAuthDTO.getAuthUserId();
                String projectId = userAuthDTO.getProjectId();
                List<String> userIdList = userAuthDTO.getUserIdList();

                iPropertyHouseHoldInfoService.updateAppUserAuth(userIdList, authUserId, projectId);
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_SDK获取用户设备权限地址队列消费者】:处理异常", e);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
